# -*- coding: UTF-8 -*-

import cherrypy

import os
import sys

import py_compile as pyc
import data as hs
reload(sys)
sys.setdefaultencoding('utf-8')
class demo(object):
    @cherrypy.expose
    def index(self):
        return open("index.html")

class adminService(object):
    exposed = True

    @cherrypy.tools.accept(media='text/plain')
    def GET(self):
        return open("admin.html")

    def POST(self, type):
        total = -1
        if type == "index":
            total = hs.update_index()
        elif type == "stock":
            total = hs.update_stock()
        return total

class myStocksService(object):
    exposed = True

    @cherrypy.tools.accept(media='text/plain')
    def GET(self):
        return open("mystocks.html")

    def POST(self, code="600570"):
        data = ""
        valid = True
        print code
        if len(code) != 6:
            valid = False
        for index in (0,5):
            if code[index].isdigit() == False:
                valid = False
                break
        if valid:
            data = hs.get_beta_data(code)
        return data

class calendarService(object):
    exposed = True

    @cherrypy.tools.accept(media='text/plain')
    def GET(self):
        return open("mystocks.html")

    def POST(self, code="600570"):
        data = ""
        valid = True
        if len(code) != 6:
            valid = False
        for index in (0,5):
            if code[index].isdigit() == False:
                valid = False
                break
        if valid:
            data = hs.get_calendar_data(code)
        return data

if __name__ == '__main__':
    pyc.compile("data.py")
    conf = {
         '/': {
             'tools.sessions.on': True,
             'tools.staticdir.root': os.path.abspath(os.getcwd())
         },
        '/admin': {
          'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
          'tools.response_headers.on': True,
          'tools.response_headers.headers': [('Content-Type', 'html')],
        },
        '/mystocks': {
         'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
         'tools.response_headers.on': True,
         'tools.response_headers.headers': [('Content-Type', 'html')],
        },
        '/calendar': {
          'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
          'tools.response_headers.on': True,
          'tools.response_headers.headers': [('Content-Type', 'html')],
        },
        '/static': {
         'tools.staticdir.on': True,
         'tools.staticdir.dir': './public'
        }
    }
    webapp = demo()
    webapp.admin = adminService()
    webapp.mystocks = myStocksService()
    webapp.calendar = calendarService()
    cherrypy.quickstart(webapp, '/', conf)
